using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using CMS.BIZ;
using FredCK.FCKeditorV2;
using System.Web.Security;

namespace CMS.Web.UI.UserControls
{
    public class Forum : UserControl
    {

        private BizForum forum;
        private BizForumPost post;
        private BizForumMessage message;
        private bool isModerator;
        private BizMembershipUser user;

        protected PlaceHolder phForum;
        protected Repeater repeaterCategory;

        protected PlaceHolder phPost;
        protected Repeater repeaterPost;

        protected PlaceHolder phMessage;
        protected HyperLink hlEditPost;
        protected HyperLink hlDeletePost;
        protected Repeater repeaterMessage;

        protected PlaceHolder phCreate;
        protected TextBox tbTitle;
        protected FCKeditor wysiwygMessage;
        protected Button bSend;

        public Forum()
        {
            base.Init += new EventHandler(Forum_Init);
        }

        public BizForum BizForum 
        { 
            get 
            {
                if (forum == null) SetForumFromQueryString();
                return forum; 
            } 
        }
        public BizForumPost BizPost 
        { 
            get 
            {
                if (post == null) SetPostFromQueryString();
                return post; 
            } 
        }

        public string QueryStringForum { get { return Page.QueryStringPage + "&Forum=" + forum.ForumID; } }
        public string QueryStringPost { get { return Page.QueryStringPage + "&Forum=" + post.ForumID + "&Post=" + post.ForumPostID; } }
        public string QueryStringMessage { get { return QueryStringPost + "&Message=" + message.ForumMessageID; } }

        public bool CanChangePost { get { return isModerator || (post.MemberID != null && user != null && user.MemberID == post.MemberID); } }
        public bool CanChangeMessage { get { return isModerator || (message.MemberID != null && user != null && user.MemberID == message.MemberID); } }

        void Forum_Init(object sender, EventArgs e)
        {
            repeaterCategory.ItemDataBound += new RepeaterItemEventHandler(Category_ItemDataBound);
            repeaterMessage.ItemDataBound += new RepeaterItemEventHandler(Message_ItemDataBound);
            bSend.Click += new EventHandler(Send_Click);
            isModerator = Roles.IsUserInRole("Moderator");
            user = Page.BizMembershipUser;
            if (!Page.IsPostBack)
            {
                SetForumFromQueryString();
                SetPostFromQueryString();
                SetMessageFromQueryString();
                phCreate.Visible = false;
                phForum.Visible = false;
                phPost.Visible = false;
                phMessage.Visible = false;
                string editStr = Request.QueryString["Edit"];
                string deleteStr = Request.QueryString["Delete"];
                if (!string.IsNullOrEmpty(deleteStr))
                {
                    if (deleteStr == "Post" && post != null && CanChangePost)
                    {
                        Page.BizForumPostProvider.Delete(post.ForumPostID);
                        Page.BizForumMessageProvider.DeleteByPostID(post.ForumPostID);
                        Response.Redirect(QueryStringForum);
                    }
                    else if (deleteStr == "Message" && message != null && CanChangeMessage) Page.BizForumMessageProvider.Delete(message.ForumMessageID);
                }
                if (!string.IsNullOrEmpty(Request.QueryString["Create"]))
                {
                    phCreate.Visible = true;
                }
                else if (!string.IsNullOrEmpty(editStr))
                {
                    if (editStr == "Post" && post != null && CanChangePost)
                    {
                        phCreate.Visible = true;
                        tbTitle.Text = post.PostTitle;
                        wysiwygMessage.Value = post.PostMessage;
                    } else if(editStr == "Message" && message != null && CanChangeMessage) 
                    {
                        phCreate.Visible = true;
                        tbTitle.Text = message.MessageTitle;
                        wysiwygMessage.Value = message.Message;
                    }
                }
                else if (post != null)
                {
                    string baseQuery = QueryStringPost;
                    phMessage.Visible = true;
                    BindMessage();
                    if (CanChangePost)
                    {
                        hlDeletePost.NavigateUrl = baseQuery + "&Delete=Post";
                        hlEditPost.NavigateUrl = baseQuery + "&Edit=Post";
                    }
                    else
                    {
                        hlDeletePost.Visible = hlEditPost.Visible = false;
                    }
                }
                else if (forum != null)
                {
                    phPost.Visible = true;
                    BindPost();
                }
                else
                {
                    phForum.Visible = true;
                    BindCategory();
                }
            }
        }

        void Message_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            BizForumMessage message = (BizForumMessage)e.Item.DataItem;
            if (message == null) return;
            string baseQuery = QueryStringPost + "&Message=" + message.ForumMessageID.ToString();
            HyperLink linkEdit = (HyperLink)e.Item.FindControl("hlEditMessage");
            HyperLink linkDelete = (HyperLink)e.Item.FindControl("hlDeleteMessage");
            if (isModerator || (message.MemberID != null && user != null && user.MemberID == message.MemberID))
            {
                linkDelete.NavigateUrl = baseQuery + "&Delete=Message";
                linkEdit.NavigateUrl = baseQuery + "&Edit=Message";
            }
            else
            {
                linkEdit.Visible = linkDelete.Visible = false;
            }
        }

        private void BindMessage()
        {
            List<BizForumMessage> list = Page.BizForumMessageProvider.ReadAllByPost(post.ForumPostID);
            repeaterMessage.DataSource = list;
            repeaterMessage.DataBind();
        }

        private void SetPostFromQueryString()
        {
            string str = Request.QueryString["Post"];
            if (!string.IsNullOrEmpty(str)) post = Page.BizForumPostProvider.Find(int.Parse(str));
        }

        protected void Send_Click(object sender, EventArgs e)
        {
            BizMembershipUser user = Page.BizMembershipUser;
            string forumStr = Request.QueryString["Forum"];
            string postStr = Request.QueryString["Post"];
            string messageStr = Request.QueryString["Message"];
            bool create = !string.IsNullOrEmpty(Request.QueryString["Create"]);
            if (!string.IsNullOrEmpty(messageStr))
            {
                BizForumMessage temp = null;
                if (message == null) SetMessageFromQueryString();
                if (message == null) return;
                if (create)
                {
                    temp = new BizForumMessage();
                    temp.ForumPostID = message.ForumPostID;
                    temp.ParentMessageID = message.ForumMessageID;
                    if (user != null) temp.MemberID = user.MemberID;
                }
                else
                {
                    if (!CanChangeMessage) return;
                    temp = message;
                    temp.LastModifDate = DateTime.Now;
                    if (user != null) temp.LastModifMemberID = user.MemberID;
                }
                temp.MessageTitle = tbTitle.Text;
                temp.Message = wysiwygMessage.Value;
                if (create) Page.BizForumMessageProvider.Create(temp);
                else Page.BizForumMessageProvider.Update(temp);
                Response.Redirect(QueryStringMessage);
            }
            else if (!string.IsNullOrEmpty(postStr))
            {
                if (post == null) SetPostFromQueryString();
                if (post == null) return;
                if (create)
                {
                    message = new BizForumMessage();
                    message.ForumPostID = post.ForumPostID;
                    if (user != null) message.MemberID = user.MemberID;
                    message.MessageTitle = tbTitle.Text;
                    message.Message = wysiwygMessage.Value;
                    Page.BizForumMessageProvider.Create(message);
                    Response.Redirect(QueryStringMessage);
                }
                else
                {
                    if (!CanChangePost) return;
                    post.LastModifDate = DateTime.Now;
                    if(user != null) post.LastModifMemberID = user.MemberID;
                    post.PostTitle = tbTitle.Text;
                    post.PostMessage = wysiwygMessage.Value;
                    Page.BizForumPostProvider.Update(post);
                    Response.Redirect(QueryStringPost);
                }
            }
            else if (!string.IsNullOrEmpty(forumStr))
            {
                if (forum == null) SetForumFromQueryString();
                if (forum == null) return;
                if (create) 
                {
                    post = new BizForumPost();
                    if(user != null) post.MemberID = user.MemberID;
                }
                else
                {
                    if (!CanChangePost) return;
                    if(user != null) post.LastModifMemberID = user.MemberID;
                    post.LastModifDate = DateTime.Now;
                }
                post.ForumID = forum.ForumID;
                post.PostMessage = wysiwygMessage.Value;
                post.PostTitle = tbTitle.Text;
                if (create) Page.BizForumPostProvider.Create(post);
                else Page.BizForumPostProvider.Update(post);
                Response.Redirect(QueryStringPost);
            }
        }

        private void SetMessageFromQueryString()
        {
            string str = Request.QueryString["Message"];
            if (!string.IsNullOrEmpty(str)) message = Page.BizForumMessageProvider.Find(int.Parse(str));
        }

        private void BindPost()
        {
            repeaterPost.DataSource = Page.BizForumPostProvider.ReadAllByForum(forum.ForumID);
            repeaterPost.DataBind();
        }

        private void SetForumFromQueryString()
        {
            string str = Request.QueryString["Forum"];
            if (!string.IsNullOrEmpty(str)) forum = Page.BizForumProvider.Find(int.Parse(str));
        }

        protected void Category_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            BizForumCategory category = (BizForumCategory)e.Item.DataItem;
            if (category != null)
            {
                Repeater repeaterForum = (Repeater)e.Item.FindControl("repeaterForum");
                repeaterForum.DataSource = Page.BizForumProvider.ReadAllByCategory(category.ForumCategoryID);
                repeaterForum.DataBind();
            }
        }

        private void BindCategory()
        {
            repeaterCategory.DataSource = Page.BizForumCategoryProvider.ReadAll("ForumCategoryName");
            repeaterCategory.DataBind();
        }

    }
}
